package com.zysc.processflow.common.base;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;

public class BaseController<T extends BaseEntity> {
    IService service;

    public BaseController(IService service) {
        this.service = service;
    }

    @ApiOperation("添加/更新实体")
    @PostMapping(value = "SaveOrUpdate")
    public ResponseEntity SaveOrUpdate(@RequestBody T entity) {
        Long tm = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        Boolean b;
        entity.setCreatetime(System.currentTimeMillis());
        if (entity.getId() == null || entity.getId() == 0) {
            entity.setId((long) (System.currentTimeMillis()*Math.random()));
                entity.setCreatetime(tm);
        } else {
            entity.setUpdatetime(tm);
        }
        b = service.saveOrUpdate(entity);
        return ResponseEntity.ok(b);
//        Boolean b;
//        b = service.saveOrUpdate(entity);
//        return ResultBody.Success(b);
    }


    @ApiOperation("批量添加实体")
    @PostMapping(value = "BatchSave")
    @Transactional
    public ResponseEntity BatchSave(@RequestBody List<T> list) {
        Boolean b = false;
        b = service.saveBatch(list);
        return ResponseEntity.ok(b);
    }

    @ApiOperation("按id删除实体")
    @GetMapping(value = "DeleteById")
    @Transactional
    public ResponseEntity DeleteById(String id) {
        Boolean b = service.removeById(id);
        return ResponseEntity.ok(b);
    }

//    @ApiOperation("批量删除实体")
//    @PostMapping(value = "batchDelete")
//    @Transactional
//    public ResultBody batchDelete(@RequestParam Map<String, Object> params) {
//        Boolean b = service.removeByMap(params);
//        return ResultBody.Success(b);
//    }

    @ApiOperation("获取单个实体")
    @GetMapping("GetById")
    public ResponseEntity GetById(String id) {
        Object res = service.getById(id);
        return ResponseEntity.ok(res);

    }

    @ApiOperation("获取数据列表")
    @GetMapping("GetList")
    public ResponseEntity GetList(Integer pageIndex,Integer pageSize) {
        List<T> res;
        Long total = null;
        if (pageIndex != null && pageSize != null) {
            Page<T> p = (Page<T>) service.page(new Page(pageIndex, pageSize));
            res = p.getRecords();
            total = p.getTotal();
        } else {
            res = service.list();
        }
        return ResponseEntity.ok(new PageResult<>(total, res));
    }
}
